<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data: { type: Object as () => any, required: true },
    callBack: { type: Function as () => any, defualt: () => {} },
    other: { type: Object as () => any, default: [] },
  });

  const option = ref<any>({
    tooltip: {
      trigger: 'item',
      formatter: function (params: any) {
        let html = `<div>${params.seriesName}</div>`;
        if (props.other && props.other.length > 0 && props.other[params.dataIndex] < 0) {
          html += `
            <div style="display: flex; align-items: center; margin-top: 4px;">
              <span
                style="display: inline-block; width: 10px; height: 10px; border-radius: 50%;
                       background-color: ${params.color}; margin-right: 8px;"
              ></span>
              <span>${params.name}: ${props.other[params.dataIndex]}%</span>
            </div>
          `;
        } else {
          html += `
            <div style="display: flex; align-items: center; margin-top: 4px;">
              <span
                style="display: inline-block; width: 10px; height: 10px; border-radius: 50%;
                       background-color: ${params.color}; margin-right: 8px;"
              ></span>
              <span>${params.name}: ${params.value}%</span>
            </div>
          `;
        }
        // params.forEach((item: any) => {
        //   let value = item.value;
        //   if (item.value <= 0 && props.other && props.other.length > 0) {
        //     value = props.other[params.dataIndex];
        //   }
        //   html += `
        //     <div style="display: flex; align-items: center; margin-top: 4px;">
        //       <span
        //         style="display: inline-block; width: 10px; height: 10px; border-radius: 50%;
        //                background-color: ${item.color}; margin-right: 8px;"
        //       ></span>
        //       <span>${item.seriesName}: ${value}</span>
        //     </div>
        //   `;
        // });
        return html;
      },
    },
    series: [
      {
        animationDelay() {
          return Math.random() * 400;
        },
        animationEasing: 'exponentialInOut',
        animationType: 'scale',
        center: ['50%', '50%'],
        color: ['#5070dd', '#b6d634', '#505372', '#ff994d'],
        data: props.data ?? [],
        name: '成材率%',
        radius: ['14%', '50%'],
        roseType: 'area',
        type: 'pie',
        label: {
          show: true,
          color: '#fff',
          // formatter: '{b}{valueStyle|{c}}%', // 给 {c} 绑定专属样式
          formatter: (params: any) => {
            const rateValue = props.other?.[params.dataIndex] ?? 0;
            return `{nameStyle|${params.name}} {valueStyle|${rateValue}}%`;
          },
          rich: {
            valueStyle: {
              fontSize: 18,
              padding: [0, 2, 3, 2],
              color: '#67e0e3',
              // position: 'outside',
              // distance: 25,
              // avoidLabelOverlap: true,
            },
          },
        },
        labelLine: {
          show: true,
          showAbove: true,
          length: 8,
          length2: 3,
          smooth: true,
        },
      },
    ],
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const initCharts = () => {
    try {
      option.value.series[0].data = props.data ?? [];
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);

        chartInstance?.on('click', (params) => {
          props.callBack(params);
        });
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };
  const updateChart = () => {
    option.value.series[0].data = props.data ?? [];
    chartInstance?.setOption(option.value);
    handleResize();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
  });

  watch(
    () => [props.data],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };
</script>
<template>
  <div ref="chartRef" class="chart-container">
    <!-- <m-echarts :option="option"></m-echarts> -->
  </div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
